package com.mzba.easy.weibo.ui;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.mzba.easy.weibo.R;

/**
 * 
 * @author 06peng
 *
 */
public class WebViewActivity extends Activity {
	
	private WebView webView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_PROGRESS);    //设置Activity显示进度条
		setContentView(R.layout.oauth_webview);
		webView = (WebView)this.findViewById(R.id.webView);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setBuiltInZoomControls(true);
		
		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				WebViewActivity.this.setProgress(newProgress * 100);
			}
		});
		
		Bundle extras = getIntent().getExtras();
		String url = "";
		if (extras != null) {
			if (extras.containsKey("url")) {
				url = extras.getString("url");
				webView.loadUrl(url);
			}
		}
		webView.setWebViewClient(new WebViewClient() {

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				System.out.println("url:" + url);
				
				if (url.contains("code=")) {
					String code = url.substring(url.indexOf("code=") + 5, url.length());
					if (!code.equals("")) {
						Intent intent = new Intent();
						intent.setAction("oauth_verifier");
						Bundle extras = new Bundle();
						extras.putString("code", code);
						intent.putExtras(extras);
						sendBroadcast(intent);
						WebViewActivity.this.finish();
						return;
					}
				}
				
			}
			
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {   
				handler.proceed();
			}   

			
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
			}
		});
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (webView.canGoBack()) {
				webView.goBack(); 
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
}
